#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <db.h>
#include "amessage.pb-c.h"
#define MAX_MSG_SIZE 1024

int main (int argc, const char * argv[]) 
{
    AMessage *msg;
    int inputKey;
    uint8_t buf[MAX_MSG_SIZE];

    DB *dbp;           /* DB structure handle */
    DBT key, value;
    unsigned int flags;/* database open flags */
    int ret;           /* function reture value */
    flags = DB_RDONLY;

    if (argc != 2) {
        fprintf(stderr, "usage: reader key \n");
        exit(1);
    }
    inputKey = atoi(argv[1]);

    /* open the database */
    ret = db_create(&dbp, NULL, 0);
    if (ret != 0) {
        /* Error handling goes here */
        exit(1);
    }

    /* open DB */
    ret = dbp->open(dbp, NULL, "./my.db", NULL, DB_HASH, flags, 0);
    if (ret != 0) {
        /* Error handling */
        fprintf(stderr, "Openning DB failed ... \n");
        if (dbp != NULL) {
            dbp->close(dbp, 0);
        }
        exit(1);
    }

    memset(&key, 0, sizeof(DBT));
    memset(&value, 0, sizeof(DBT));

    key.data = &inputKey;
    key.size = sizeof(int);

    ret = dbp->get(dbp, NULL, &key, &value, 0);
    if (ret != 0) {
        /* Error handling */
        fprintf(stderr, "dbp-get: %s\n", db_strerror(ret));
        if (dbp != NULL) {
            dbp->close(dbp, 0);
        }
        exit(1);
    }

    if (value.size == 0) {
        fprintf(stderr, "Error: Read %d bytes of data\n", value.size);
        if (dbp != NULL) {
            dbp->close(dbp, 0);
        }
        exit(1);
    }


    // Unpack the message using protobuf-c.
    msg = amessage__unpack(NULL, value.size, value.data);   
    if (msg == NULL)
    {
        fprintf(stderr, "error unpacking incoming message\n");
        if (dbp != NULL) {
            dbp->close(dbp, 0);
        }
        exit(1);
    }

    // display the message's fields.
    printf("Received: a=%d",msg->a);  // required field
    if (msg->has_b)                   // handle optional field
        printf("  b=%d",msg->b);
    printf("\n");

    // Free the unpacked message
    amessage__free_unpacked(msg, NULL);

    /* close DB */
    if (dbp != NULL) {
        dbp->close(dbp, 0);
    }

    return 0;
}

///:~

